package cn.yeyiu.netonlinevideo.adapter;

import android.content.Context;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

import cn.yeyiu.netonlinevideo.R;
import cn.yeyiu.netonlinevideo.util.TargetUtil;
import cn.yeyiu.util.MediaUtil;
import cn.yeyiu.util.bean.MediaData;

/**
 * 具体view渲染，点击事件
 */

public class ListDataAdapter extends RecyclerView.Adapter<ListDataAdapter.ViewHolder> {

    private final Context mContext;
    private List<MediaData> dataList;

    public ListDataAdapter(Context context) {
        mContext = context;
    }

    public void updateList(List<MediaData> dataList) {
        this.dataList = dataList;
        this.notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = LayoutInflater.from(mContext).inflate(R.layout.item_blog_preview, parent, false);
        return new ViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MediaData mediaData = dataList.get(position);
        holder.title.setText(mediaData.title);
        holder.description.setText(mediaData.description);
        holder.time.setText(mediaData.id);
        if (mediaData.logo.length() > 1000) {
            byte[] pivc = Base64.decode(mediaData.logo, Base64.DEFAULT);
            Glide.with(mContext)
                    .load(pivc)
                    .placeholder(R.drawable.pic_local)
                    .into(holder.img);
        } else {
            Glide.with(mContext)
                    .load(mediaData.logo)
                    .placeholder(R.drawable.pic_local)
                    .into(holder.img);
        }

        holder.itemView.setOnClickListener(v -> {
            TargetUtil.go(mContext, mediaData);
        });
    }

    @Override
    public int getItemCount() {
        if (dataList == null) {
            return 0;
        }
        return dataList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView title;
        public ImageView img;
        public TextView description;
        public TextView time;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.data_pic_img);
            title = itemView.findViewById(R.id.data_title_tv);
            description = itemView.findViewById(R.id.data_description);
            time = itemView.findViewById(R.id.data_time);
        }
    }
}
